#!/usr/bin/python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: dictionary.py
# Description: 
# 
# Edit History: 
#   2011-07-28    File created.
#===============================================================================


def readFile(fileHandle): 
    line = fileHandle.readline() 
    dictName = {} 
    keycounter = 1 

    while line: 
        key = str(keycounter) 
        dictName[key] = line 
        keycounter = keycounter + 1 
        line = fileHandle.readline() 

    return dictName

def demo_keys():
    dic = {'k1': 'v1',
           'k2': 'v2'
          }
    print dic.keys()
    print dic.keys()[0]

global_dic = {'a':'1', 'b':'2', 'c':'3'}
count = 0

def round_keys():
    global count
    print "[", len(global_dic.keys()), global_dic.keys()[count%len(global_dic.keys())], count, "]"
    count += 1

def demo_round_keys():
    round_keys()
    round_keys()
    round_keys()
    round_keys()
    round_keys()
    round_keys()

def sort_keys_python2_4_greater(dic):
    for key in sorted(dic.iterkeys()):
        print "%s: %s" % (key, dic[key])


# 1. 最簡單的方法，這個是按照key值排序：
def sort_keys_fun1(dic):
    items = dic.items()
    items.sort()
    for key, value in items:
        print "%s: %s" % (key, value)

    return [value for key, value in items]

# 2. 又一個按照key值排序，貌似比上一個速度要快點
def sort_keys_python2_4_older(dic):
    keylist = dic.keys()
    keylist.sort()
    for key in keylist:
        print "%s: %s" % (key, dic[key])
    return [dic[key] for key in keylist]

# 3. 還是按key值排序，據說更快。 。 。而且當key為tuple的時候照樣適用
# a further slight speed-up on my box
# is to map a bound-method:
def sort_keys_fun2(dic):
    keys = dic.keys()
    keys.sort()
    return map(dic.get, keys)        

#一行語句搞定： 
def sort_keys_fun3(dic):
    return [(k,dic[k]) for k in sorted(dic.keys())] 


#用sorted函數的key= 參數排序： 
# 按照key進行排序
def sort_keys_lambda1(dic):
    return sorted(dic.items(), key=lambda d: d[0]) 


def sort_values_python2_4_greater(dic):
    for key, value in sorted(dic.iteritems(), key=lambda (k,v): (v,k)):
        print "%s: %s" % (key, value)


#來一個根據value排序的，先把item的key和value交換位置放入一個list中，
#再根據list每個元素的第一個值，即原來的value值，排序： 
def sort_values_fun1(dic): 
    items=dic.items() 
    backitems=[[v[1],v[0]] for v in items] 
    backitems.sort() 
    return [ backitems[i][1] for i in range(0,len(backitems))] 

#還是一行搞定： 
def sort_values_fun2(dic):
    return [ v for v in sorted(dic.values())] 

#用lambda表達式來排序，更靈活： 
def sort_values_fun3(dic):
    return sorted(dic.items(), lambda x, y: cmp(x[1], y[1]))

#反序： 
def sort_values_fun4(dic):
    return sorted(dic.items(), lambda x, y: cmp(x[1], y[1]), reverse=True) 


# 按照value進行排序
def sort_values_lambda1(dic):
    return sorted(dic.items(), key=lambda d: d[1]) 

def main():
    """
    dic = readFile(open('dictionary.py', 'r'))
    for k in dic.keys():
        print k + ' => ' + dic[k]
    """
    #demo_keys()

    #demo_round_keys()

    mydict = {'carl':40,
              'eagle':-10,
              'alan':2,
              'bob':1,
              'danny':3}

    #對dictionary排序的方法，其實它們的核心思想都一樣，即把dictionary中的元素分離出來放到一個list中，
    #對list排序，從而間接實現對dictionary的排序。這個“元素”可以是key，value或者item
    #sort_keys_python2_4_greater(mydict)
    #print sort_keys_python2_4_older(mydict)
    #print sort_keys_fun1(mydict)
    #print sort_keys_fun2(mydict)
    #print sort_keys_fun3(mydict)
    #print sort_keys_lambda1(mydict)

    #sort_values_python2_4_greater(mydict)
    #print sort_values_fun1(mydict)
    #print sort_values_fun2(mydict)
    #print sort_values_fun3(mydict)
    #print sort_values_fun4(mydict)
    #print sort_values_lambda1(mydict)


if __name__=="__main__":
    main()
